package com.dayu.web.controller;

import java.io.Writer;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dayu.finecomm.aop.ClassLevelAnnotation;
import com.dayu.finecomm.aop.MethodLevelAnnotation;
import com.dayu.finecomm.iot.IotConsole;
import com.dayu.finecomm.iot.params.IotAopParam;
import com.dayu.finecomm.iot.params.IotCmdParam;
import com.dayu.finecomm.iot.params.IotDeviceParam;
import com.dayu.finecomm.iot.params.IotLogParam;
import com.dayu.finecomm.iot.params.IotPlatParam;
import com.dayu.finecomm.iot.params.IotQueryDataParam;

/**
 * Iot Controller
 * 
 * @author XuJialiang
 * @since 2017-09-04 10:22:12
 * @version V1.0.0
 */
@Controller
@RequestMapping("/iot")
@ClassLevelAnnotation
public class IotCtrl {

	/**
	 * 浏览配置界面，暂不实现该功能
	 * 
	 * @param idAction
	 * @param writer
	 * @throws InterruptedException
	 */
	@MethodLevelAnnotation
	@RequestMapping(value = "/ycb/{idAction:\\w+}.html", method = RequestMethod.GET)
	public void htmlView(@PathVariable String idAction, Writer writer)
			throws InterruptedException {
		// if (0 == idAction.compareTo("iotplat")) {
		// String strHTML = "/iot/ycb/iotplat.html";
		// }

		StringBuffer sbHtml = new StringBuffer();
		sbHtml.append("<!doctype html><html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
		sbHtml.append("<title>IotNorth</title></head><body>Hello HDKJ!</body></html>");
		try {
			writer.write(sbHtml.toString());
		} catch (Exception e) {
			System.out.println("ERROR");
		}
	}

	@RequestMapping(value = "/ycb/queryLog/", method = RequestMethod.POST)
	@ResponseBody
	public JSONObject queryLog(@RequestBody IotLogParam params)
			throws Exception {
		String result = IotConsole.getInstance().handleIotQueryLog(params);
		JSONObject jsonContent = JSON.parseObject(result);

		return jsonContent;
	}

	@RequestMapping(value = "/ycb/queryAop/", method = RequestMethod.POST)
	@ResponseBody
	public JSONObject queryAop(@RequestBody IotAopParam params)
			throws Exception {
		String result = IotConsole.getInstance().handleIotQueryAop(params);
		JSONObject jsonContent = JSON.parseObject(result);

		return jsonContent;
	}

	/**
	 * 创建或者修改App
	 * 
	 * @param params
	 * @return
	 * @throws Exception
	 */
	@MethodLevelAnnotation
	@RequestMapping(value = "/ycb/createapp/", method = RequestMethod.POST)
	@ResponseBody
	public JSONObject createApp(@RequestBody IotPlatParam params)
			throws Exception {
		String result = IotConsole.getInstance().handleIotAuth(params);

		JSONObject jsonContent = JSON.parseObject(result);

		int code = jsonContent.getIntValue("Code");
		if (0 == code) {
			IotQueryDataParam subscribeParam = new IotQueryDataParam();
			subscribeParam.appid = params.appid;
			subscribeParam.subscribe = new IotQueryDataParam.Subscribe();
			subscribeParam.subscribe.subscommandRsp = 1;
			subscribeParam.subscribe.subsdeviceDatasChanged = 1;

			result = IotConsole.getInstance().subscribe(subscribeParam);

			jsonContent = JSON.parseObject(result);

			code = jsonContent.getIntValue("Code");
			if (0 == code) {
				JSONObject jsonResponse = new JSONObject();
				if (null != jsonResponse) {
					jsonResponse.put("subscommandRsp", 1);
					jsonResponse.put("subsdeviceDatasChanged", 1);

					jsonContent.put("Response", jsonResponse);
				}
			}
		}

		return jsonContent;
	}

	/**
	 * 删除APP
	 * 
	 * @param params
	 * @return
	 * @throws Exception
	 */
	@MethodLevelAnnotation
	@RequestMapping(value = "/ycb/deleteapp/", method = RequestMethod.POST)
	@ResponseBody
	public JSONObject deleteApp(@RequestBody IotPlatParam params)
			throws Exception {
		String jsonStr = IotConsole.getInstance().handleDeleteApp(params);
		JSONObject jsonContent = JSON.parseObject(jsonStr);
		return jsonContent;
	}

	/**
	 * 查询APP应用
	 * 
	 * @return
	 * @throws Exception
	 */
	@MethodLevelAnnotation
	@RequestMapping(value = "/ycb/queryapp/", method = RequestMethod.GET)
	@ResponseBody
	public JSONObject queryApp() throws Exception {
		String jsonStr = IotConsole.getInstance().handleQueryApp();
		JSONObject jsonContent = JSON.parseObject(jsonStr);
		return jsonContent;
	}

	/**
	 * 鉴权
	 * 
	 * @param params
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/ycb/iotauth/", method = RequestMethod.POST)
	@ResponseBody
	public String iotAuth(@RequestBody IotPlatParam params) throws Exception {
		return IotConsole.getInstance().handleIotAuth(params);
	}

	/**
	 * 刷新token
	 * 
	 * @param params
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/ycb/refreshToken/", method = RequestMethod.POST)
	@ResponseBody
	public String refreshToken(@RequestBody IotPlatParam params)
			throws Exception {
		return IotConsole.getInstance().handleIotRefreshToken(params);
	}

	/**
	 * NA订阅CM的设备变更
	 * 
	 * @param params
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/ycb/subscribe/", method = RequestMethod.POST)
	@ResponseBody
	public String subscribe(@RequestBody IotQueryDataParam params)
			throws Exception {
		return IotConsole.getInstance().subscribe(params);
	}

	/**
	 * 注册设备
	 * 
	 * @param params
	 * @return
	 * @throws Exception
	 */
	@MethodLevelAnnotation
	@RequestMapping(value = "/ycb/register/", method = RequestMethod.POST)
	@ResponseBody
	public JSONObject iotRegister(@RequestBody IotDeviceParam params)
			throws Exception {
		if (null == params.device) {
			params.device = new IotDeviceParam.Device();
		}
		params.device.nodeId = params.imei;
		params.device.verifyCode = params.imei;

		String result = IotConsole.getInstance().handleRegDevice(params);
		JSONObject jsonContent = JSON.parseObject(result);

		int code = jsonContent.getIntValue("Code");
		if (0 == code) {
			JSONObject rsp = jsonContent.getJSONObject("Response");
			if (null != rsp) {
				params.device.deviceId = rsp.getString("deviceId");
				params.device.deviceType = params.devType;
				params.device.manufacturerId = params.mfrsId;
				params.device.manufacturerName = params.mfrsName;
				params.device.model = params.model;
				params.device.protocolType = params.protocolType;

				String tmp = IotConsole.getInstance().handleSetDevice(params);
				JSONObject jsonTmp = JSON.parseObject(tmp);

				code = jsonTmp.getIntValue("Code");
				if (0 != code) {
					IotConsole.getInstance().handleDeleteDevice(params);
					jsonContent = jsonTmp;
				}
			}
		}

		return jsonContent;
	}

	/**
	 * 设置设备信息
	 * 
	 * @param params
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/ycb/setDevInfo/", method = RequestMethod.POST)
	@ResponseBody
	public String setDevInfo(@RequestBody IotDeviceParam params)
			throws Exception {
		return IotConsole.getInstance().handleSetDevice(params);
	}

	/**
	 * 查询设备激活状态
	 * 
	 * @param params
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/ycb/queryDevStatus/", method = RequestMethod.POST)
	@ResponseBody
	public String queryDevStatus(@RequestBody IotDeviceParam params)
			throws Exception {
		return IotConsole.getInstance().handleQueryDeviceState(params);
	}

	/**
	 * 删除设备
	 * 
	 * @param params
	 * @return
	 * @throws Exception
	 */
	@MethodLevelAnnotation
	@RequestMapping(value = "/ycb/deleteDevice/", method = RequestMethod.POST)
	@ResponseBody
	public JSONObject deleteDevice(@RequestBody IotDeviceParam params)
			throws Exception {
		if (null == params.device) {
			params.device = new IotDeviceParam.Device();
		}
		params.device.deviceId = params.deviceId;
		String jsonStr = IotConsole.getInstance().handleDeleteDevice(params);

		JSONObject jsonContent = JSON.parseObject(jsonStr);
		return jsonContent;
	}

	/**
	 * 设置应用信息
	 * 
	 * @param params
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/ycb/setApplication/", method = RequestMethod.POST)
	@ResponseBody
	public String setApplication(@RequestBody IotDeviceParam params)
			throws Exception {
		return IotConsole.getInstance().handleSetApplication(params);
	}

	/**
	 * 更新位置信息
	 * 
	 * @param params
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/ycb/updateLocation/", method = RequestMethod.POST)
	@ResponseBody
	public String updateLocation(@RequestBody IotDeviceParam params)
			throws Exception {
		return IotConsole.getInstance().handleUpdateLocation(params);
	}

	/**
	 * 按条件批量查询设备信息表
	 * 
	 * @param params
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/ycb/queryAllDevs/", method = RequestMethod.POST)
	@ResponseBody
	public String queryAllDev(@RequestBody IotQueryDataParam params)
			throws Exception {
		return IotConsole.getInstance().handleQueryAllDevices(params);
	}

	/**
	 * 查询单个设备信息
	 * 
	 * @param params
	 * @return
	 * @throws Exception
	 */
	@MethodLevelAnnotation
	@RequestMapping(value = "/ycb/queryDev/", method = RequestMethod.POST)
	@ResponseBody
	public JSONObject queryDev(@RequestBody IotQueryDataParam params)
			throws Exception {
		params.devCond = new IotQueryDataParam.QueryDeviceCond();
		params.devCond.deviceId = params.deviceId;

		String jsonStr = IotConsole.getInstance().handleQueryDevice(params);

		JSONObject jsonContent = JSON.parseObject(jsonStr);
		return jsonContent;
	}

	/**
	 * 查询设备的历史数据
	 * 
	 * @param params
	 * @return
	 * @throws Exception
	 */
	@MethodLevelAnnotation
	@RequestMapping(value = "/ycb/queryHistory/", method = RequestMethod.POST)
	@ResponseBody
	public JSONObject queryHistory(@RequestBody IotQueryDataParam params)
			throws Exception {
		params.historyCond = new IotQueryDataParam.QueryHistoryCond();
		params.historyCond.deviceId = params.deviceId;
		params.historyCond.gatewayId = params.deviceId;
		params.historyCond.startTime = params.startTime;
		params.historyCond.endTime = params.endTime;

		String jsonStr = IotConsole.getInstance().handleQueryHistoryDevice(
				params);

		JSONObject jsonContent = JSON.parseObject(jsonStr);
		return jsonContent;
	}

	/**
	 * 查询设备的服务能力
	 * 
	 * @param params
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/ycb/queryCapability/", method = RequestMethod.POST)
	@ResponseBody
	public String queryCapability(@RequestBody IotQueryDataParam params)
			throws Exception {
		return IotConsole.getInstance().handleQueryDeviceCapability(params);
	}

	/**
	 * 向设备投递命令
	 * 
	 * @param params
	 * @return
	 */
	@MethodLevelAnnotation
	@RequestMapping(value = "/ycb/postCmd/", method = RequestMethod.POST)
	@ResponseBody
	public JSONObject postCmd(@RequestBody IotCmdParam params) {
		params.postCmd = new IotCmdParam.PostCmd();

		params.postCmd.deviceId = params.deviceId;
		params.postCmd.command = new IotCmdParam.PostCmd.Command();
		params.postCmd.command.method = params.method;
		params.postCmd.command.paras = params.paras;
		params.postCmd.command.serviceId = "WaterMeter";

		if (0 == "SET_HIGHFLOW_ALARM".compareTo(params.method)) {
			params.postCmd.command.serviceId = "WaterMeterAlarm";
		}

		String jsonStr = IotConsole.getInstance().handlePostCmdToDevice(params);

		JSONObject jsonContent = JSON.parseObject(jsonStr);
		return jsonContent;
	}

	/**
	 * 按条件批量查询命令
	 * 
	 * @param params
	 * @return
	 */
	@RequestMapping(value = "/ycb/queryCmds/", method = RequestMethod.POST)
	@ResponseBody
	public String queryCmds(@RequestBody IotCmdParam params) {
		return IotConsole.getInstance().handleQueryDeviceCmds(params);
	}

	/**
	 * 修改命令
	 * 
	 * @param params
	 * @return
	 */
	@RequestMapping(value = "/ycb/modifyCmds/", method = RequestMethod.POST)
	@ResponseBody
	public String modifyCmds(@RequestBody IotCmdParam params) {
		return IotConsole.getInstance().handleModifyCmds(params);
	}

	/**
	 * 查询单个命令
	 * 
	 * @param params
	 * @return
	 */
	@MethodLevelAnnotation
	@RequestMapping(value = "/ycb/queryCmd/", method = RequestMethod.POST)
	@ResponseBody
	public JSONObject queryCmd(@RequestBody IotCmdParam params) {
		params.queryCmd = new IotCmdParam.QueryCmd();
		params.queryCmd.deviceId = params.deviceId;
		params.queryCmd.commandId = params.commandId;

		String jsonStr = IotConsole.getInstance().handleQueryDeviceCmd(params);

		JSONObject jsonContent = JSON.parseObject(jsonStr);
		return jsonContent;
	}
}
